/**
 * @description: 单镜头tab js 文件
 * @fileName: index
 * @author: 17076
 * @date: 2025/4/14-下午3:43
 * @version: V1.0.0
 **/
import fullscreen from 'screenfull'
import Swiper from 'swiper'
import 'swiper/css/swiper.css'
import { baseURL, wsUrl } from '@/config/net.config'
import { commonDownloadFile, commonSaveFile, commonUploadFile, deleteFile, uploadFile } from '@/api/config/uploadApi'
import { detectLanguage, htmlToText } from '@/utils'
import {
  addLensFrame,
  queryFrameHistory,
  queryLensCoverHistory,
  queryLensListByFrameId,
  textToImages,
  uploadFrameImage,
  moveLensFrame, deleteLensFrame, setLensFrame,
  deleteGenerateHistory,
  clearGenerateHistory, chineseToEnglish, queryUserFrameProgress, cancelLensFrame, queryAllTagsList
} from '@/api/lens'
import WS from '@/utils/webScoket'
import { mapGetters } from 'vuex'
import SelectLens from '@/views/creativeCenter/playWriting/components/lens/others/SelectLens.vue'
import { selectFinishedRole } from '@/api/roles'
import MoreTag from '@/views/creativeCenter/playWriting/components/lens/others/MoreTag.vue'
export default {
  name: 'Index',
  components: { MoreTag, SelectLens },
  props: {
    playId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      // ws 实例
      ws: null,
      // swiper实例
      swiper: null,
      // 是否显示图片预览
      showImageViewer: false,
      // 初始图片下标
      initialIndex: 0,
      // 当前选中的镜头下标
      currentLensIndex: 0,
      // 生成历史镜头下标
      currentGenerateHistoryImageId: null,
      // 选中历史镜头
      currentHistoryImage: 0,
      // 选中历史镜头数据
      currentHistoryImageData: {},
      // 选中的生成之后的图片下标
      currentGenerateImage: null,
      // 更多参数
      showDetails: true,
      // 正在生成
      generateLoading: false,
      // 正在翻译
      translating: false,
      // 是否显示提示词
      isShowPrompt: '1',
      // 图片宽高更新锁
      updateLock: false,
      // 提示词是否全屏
      isFullscreen: false,
      // 区分是提示词的本地图片上传还是，还是镜头上传
      isLensUpload: false,
      // 右侧镜头区更多参数显示
      showMore: true,
      // 显示角色弹窗
      showRolePopup: false,
      // 记录光标位置
      cursorPosition: 0,
      // 全部镜头列表
      allLensList: [],
      // 提示词标签列表
      allTagsList: [
        { label: '景别', value: 0, children: [
          { label: '自然1', value: 1, type: '1' },
          { label: '人文1', value: 2, type: '1' },
          { label: '建筑发i就发觉1', value: 3, type: '1' },
          { label: '建筑1', value: 3, type: '1' },
          { label: '建筑1', value: 3 },
          { label: '建发酵饲料客服就爱上了附件爱丽丝筑1', value: 3, type: '1' },
          { label: '建筑1', value: 3, type: '1' },
          { label: '建筑1', value: 3, type: '1' },
          { label: '建筑cesfkl1', value: 3, type: '1' },
          { label: '建筑1', value: 3, type: '1' },
          { label: '建筑1', value: 3, type: '1' },
          { label: '建筑1', value: 3, type: '1' },
          { label: '建筑1', value: 3, type: '1' },
          { label: '建筑1', value: 3, type: '1' },
          { label: '建筑1', value: 3, type: '1' },
          { label: '建筑1', value: 3, type: '1' },
          { label: '建筑1', value: 3, type: '1' },
          { label: '建筑1', value: 3, type: '1' },
          { label: '建筑1', value: 3, type: '1' },
          { label: '建筑1', value: 3, type: '1' }
        ] },
        { label: '时间', value: 1, children: [{ label: '自然2', value: 1 }, { label: '人文2', value: 2 }, { label: '建筑2', value: 3 }] },
        { label: '场景', value: 2, children: [{ label: '自然3', value: 1 }, { label: '人文3', value: 2 }, { label: '建筑3', value: 3 }] },
        { label: '表情动作', value: 3, children: [{ label: '自然4', value: 1 }, { label: '人文4', value: 2 }, { label: '建筑4', value: 3 }] }
      ],
      // 选中的标签列表
      selectTagsList: [],
      // 上传参数配置
      uploadOption: {
        action: baseURL + commonUploadFile,
        headers: {
          'Auth-Token': localStorage.getItem('MyToken')
        }
      },
      // 参考素材文件列表
      fileList: [],
      // 编辑区表单
      editForm: {
        steps: 20,
        createNum: '1',
        cfg: 5.55,
        pictureScale: '8',
        imageWidth: 478,
        imageHeight: 850,
        isLink: '1',
        modelCode: '2'
      },
      // 预览图片连接
      previewImageUrl: '',
      // 编辑区校验规则
      rules: {
        modelCode: [{ required: true, message: '请选择模型!', trigger: 'blur' }],
        promptRichText: [{ required: true, message: '提示词不能为空!', trigger: 'blur' }],
        sampler: [{ required: true, message: '采样方法不能为空!', trigger: 'blur' }]
      },
      // 生成数量列表
      createNumList: [
        { name: '1 张', value: '1' },
        { name: '2 张', value: '2' },
        { name: '3 张', value: '3' },
        { name: '4 张', value: '4' }
      ],
      // 激活的标签
      activeTabs: 0,
      // 角色列表
      rolesList: [],
      // 模型列表
      modelList: JSON.parse(sessionStorage.getItem('modelType')),
      // 质量等级
      qualityList: JSON.parse(sessionStorage.getItem('qualityLevel')),
      // 画面比例
      pictureScaleList: JSON.parse(sessionStorage.getItem('pictureScale')),
      // 采样方法
      samplerList: [],
      // 是否编辑
      isEdit: false,
      // 下载连接
      downloadUrl: baseURL + commonDownloadFile,
      // 生成历史
      generateHistoryList: [],
      // 历史镜头
      historyLensList: [],
      // 正在进行文生图的图片列表
      generatingList: [],
      // 无封面时选中的生成历史
      generateHistoryRecurrence: [],
      // comfy-ui 当前正在执行的任务数量
      queueRemaining: 0,
      // 角色筛选
      searchVal: '',
      // 参考材料是否是选择镜头
      isSelectLens: false
    }
  },
  computed: {
    // 分镜数据
    ...mapGetters({
      username: 'user/username',
      selectLens: 'lens/selectLens',
      // pictureScale: 'lens/pictureScale',
      directorSelectLensId: 'lens/directorSelectLensId'
    }),
    // 根据 <input> value 筛选 list
    searchedList() {
      const searchVal = this.searchVal.trim().toLowerCase()
      return this.rolesList.filter(item => {
        const name = item.name.toLowerCase()
        if (name.indexOf(searchVal) >= 0) {
          return true
        }
        return false
      })
    }
  },
  watch: {
    // 监听表单中图片宽高的变化
    'editForm.imageWidth': {
      handler: function(val) {
        if (this.updateLock) return
        // 需要宽高比存在链接关系才可同时设置高度
        if (val && this.editForm['isLink'] === '1') {
          this.updateLock = true
          // 根据当前图片的宽高比改变
          switch (this.editForm['pictureScale']) {
            case '1':
              // 21 : 9
              this.$set(this.editForm, 'imageHeight', (val * 9 / 21).toFixed(0))
              break
            case '2':
              // 16 : 9
              this.$set(this.editForm, 'imageHeight', (val * 9 / 16).toFixed(0))
              break
            case '3':
              // 3 : 2
              this.$set(this.editForm, 'imageHeight', (val * 2 / 3).toFixed(0))
              break
            case '4':
              // 4 : 3
              this.$set(this.editForm, 'imageHeight', (val * 3 / 4).toFixed(0))
              break
            case '5':
              // 1 : 1
              this.$set(this.editForm, 'imageHeight', val)
              break
            case '6':
              // 3 : 4
              this.$set(this.editForm, 'imageHeight', (val * 4 / 3).toFixed(0))
              break
            case '7':
              // 2 : 3
              this.$set(this.editForm, 'imageHeight', (val * 3 / 2).toFixed(0))
              break
            case '8':
              // 9 : 16
              this.$set(this.editForm, 'imageHeight', (val * 16 / 9).toFixed(0))
              break
          }
        }
        this.$nextTick(() => { this.updateLock = false })
      },
      deep: true
    },
    // 监听表单中图片宽高的变化
    'editForm.imageHeight': {
      handler: function(val) {
        if (this.updateLock) return
        // 需要宽高比存在链接关系才可同时设置高度
        if (val && this.editForm['isLink'] === '1') {
          this.updateLock = true
          // 根据当前图片的宽高比改变
          switch (this.editForm['pictureScale']) {
            case '1':
              // 21 : 9
              this.$set(this.editForm, 'imageWidth', (val * 21 / 9).toFixed(0))
              break
            case '2':
              // 16 : 9
              this.$set(this.editForm, 'imageWidth', (val * 16 / 9).toFixed(0))
              break
            case '3':
              // 3 : 2
              this.$set(this.editForm, 'imageWidth', (val * 3 / 2).toFixed(0))
              break
            case '4':
              // 4 : 3
              this.$set(this.editForm, 'imageWidth', (val * 4 / 3).toFixed(0))
              break
            case '5':
              // 1 : 1
              this.$set(this.editForm, 'imageWidth', val)
              break
            case '6':
              // 3 : 4
              this.$set(this.editForm, 'imageWidth', (val * 3 / 4).toFixed(0))
              break
            case '7':
              // 2 : 3
              this.$set(this.editForm, 'imageWidth', (val * 2 / 3).toFixed(0))
              break
            case '8':
              // 9 : 16
              this.$set(this.editForm, 'imageWidth', (val * 9 / 16).toFixed(0))
              break
          }
        }
        this.$nextTick(() => { this.updateLock = false })
      },
      deep: true
    },
    // 导演反馈选中的镜头id
    directorSelectLensId: {
      handler: function(newVal, oldVal) {
        if (newVal !== oldVal) {
          this.queryLensData()
        }
      },
      deep: true
    },
    // 监听选中的分镜数据有值才调用接口
    selectLens: {
      handler: function(newVal, oldVal) {
        if (newVal && newVal['lensId'] && newVal !== oldVal) {
          this.queryLensData()
        }
      },
      immediate: true
    },
    // 监听角色弹窗弹出
    showRolePopup: {
      handler: function(newVal, oldVal) {
        if (oldVal !== newVal && newVal) {
          // 角色输入框获取焦点
          this.$nextTick(() => {
            this.$refs.roleInput.focus()
          })
        }
      }
    }
  },
  mounted() {
    this.handleWs()
    this.queryRolesList()
    this.queryPromptTagsList()
    // this.queryLensData()
    // 提示词全屏监听
    if (fullscreen.isEnabled) {
      fullscreen.on('change', this.promptFullChange)
    }
    // 监听是否点击角色列表弹窗
    document.addEventListener('click', (e) => {
      if (e.target !== document.getElementById('role-select-popup') && this.showRolePopup && !e.target.classList.contains('role-tag-item')) {
        this.showRolePopup = false
      }
    })
  },
  beforeDestroy() {
    if (fullscreen.isEnabled) {
      fullscreen.off('change', this.promptFullChange)
    }
    document.removeEventListener('click', null)
  },
  methods: {
    // 获取镜头数据
    queryLensData() {
      if (!this.selectLens['lensId']) {
        this.$baseMessage.error('请选择一条分镜数据!')
        return
      }
      queryLensListByFrameId({ lensId: this.selectLens['lensId'] }).then(res => {
        this.allLensList = res.data
        // 如果当前镜头id存在则选中当前镜头
        if (this.directorSelectLensId) {
          const index = this.allLensList.findIndex(item => item.id === this.directorSelectLensId)
          if (index !== -1) {
            this.currentLensIndex = index
          }
        }
        // 组合镜头数据
        this.handleShotDataCombination(this.currentLensIndex)
        // 查询任务进度
        this.handleQueryProgress()
        this.queryLensSettingCoverHistory()
      })
    },
    // 获取生成历史记录
    queryGenerateHistory() {
      if (!this.editForm['id'] && !this.editForm['frameId']) {
        this.$baseMessage.error('镜头id不能为空!')
        return
      }
      queryFrameHistory({ frameId: this.editForm['id'] || this.editForm['frameId'] }).then(res => {
        this.generateHistoryList = res.data
      })
    },
    // 获取镜头封面设置历史
    queryLensSettingCoverHistory() {
      if (!this.editForm['id'] && !this.editForm['frameId']) {
        this.$baseMessage.error('镜头id不能为空!')
        return
      }
      queryLensCoverHistory({ frameId: this.editForm['id'] || this.editForm['frameId'] }).then(res => {
        this.historyLensList = res.data
        if (this.historyLensList.length > 0) {
          this.currentHistoryImageData = res.data[this.currentHistoryImage] || {}
          this.initSwiper()
          this.queryGenerateHistory()
        } else {
          // 不存在历史镜头封面时默认选中生成历史第一条
          queryFrameHistory({ frameId: this.editForm['id'] || this.editForm['frameId'] }).then(res => {
            this.generateHistoryList = res.data
            if (this.generateHistoryList.length > 0) {
              const firstOne = this.generateHistoryList[0]
              this.generateHistoryRecurrence = []
              firstOne['imageList'].forEach(item => {
                this.generateHistoryRecurrence.push({ ...firstOne, imageId: item['imageId'] })
              })
              // 合并表单数据
              this.editForm = Object.assign({}, firstOne, { id: firstOne['frameId'], createNum: firstOne['imageList'].length.toString() })
              console.log('当前表单内容', this.editForm)
            } else {
              // 清空选中该数据的
              this.currentHistoryImageData = {}
            }
          })
        }
      })
    },
    // 调用查询任务进度
    handleQueryProgress() {
      queryUserFrameProgress({ frameId: this.editForm['id'] || this.editForm['frameId'] }).then(res => {
        const { taskList, typeProgress } = res.data
        this.generateLoading = typeProgress === '01'
        if (typeProgress === '01') {
          // 清空任务数据
          this.generatingList = []
          // 清空选中的历史镜头下标
          this.currentHistoryImage = null
          // 存在进行中的任务,根据数据中的createNum 设置生成数组数据
          const taskData = taskList[0]
          // 拼合数据
          this.editForm = Object.assign({}, this.editForm, taskData)
          for (let i = 0; i < taskData.createNum; i++) {
            this.generatingList.push({ ...taskData, imageId: '' })
          }
        }
      })
    },
    // 获取角色列表
    queryRolesList() {
      selectFinishedRole({ playId: this.playId }).then(res => {
        this.rolesList = res.data
        console.log('角色列表:', this.roleList)
      })
    },
    // 获取提示词标签列表
    queryPromptTagsList() {
      queryAllTagsList({}).then(res => {
        this.allTagsList = res.data || []
        if (this.allTagsList.length > 0) {
          this.activeTabs = this.allTagsList[0].id
        }
      })
    },
    // 角色弹窗输入
    inputKeyupHandler(event) {
      // esc - 隐藏 modal
      if (event.key === 'Escape') {
        this.showRolePopup = false
      }
      // enter - 插入 mention node
      if (event.key === 'Enter') {
        // 插入第一个
        const firstOne = this.searchedList[0]
        if (firstOne) {
          this.handleInsertRole(firstOne)
        }
      }
    },
    // 初始化swiper
    initSwiper() {
      if (this.swiper) {
        this.swiper.destroy()
        this.swiper = null
      }
      this.$nextTick(() => {
        // 初始化swiper
        this.swiper = new Swiper('.swiper-container', {
          loop: false,
          slidesPerView: 3,
          spaceBetween: 20,
          navigation: {
            nextEl: '.next-button', // 下一页按钮
            prevEl: '.pre-button' // 上一页按钮
          }
        })
      })
    },
    // 生成张数改变
    handleCreateNumChange(value) {
      this.$set(this.editForm, 'createNum', value)
    },
    // 格式化语言图标显示
    formatterLanguageIcon(text) {
      return detectLanguage(htmlToText(text)) === 'ch' ? 'english' : 'chinese'
    },
    // 插入提示词角色名称
    handleInsertRole(role) {
      const roleId = role['id']
      // const roleName = role['name']
      // // 根据记录的光标位置插入角色名称
      // let modifiedString = this.editForm['prompt'].split('')
      // modifiedString.splice(this.cursorPosition, 0, ...roleName)
      // modifiedString = modifiedString.join('')
      // console.log(modifiedString, 5555)
      // this.$set(this.editForm, 'prompt', modifiedString)
      // 删除对应文本中的#
      // console.log(this.cursorPosition, this.editForm['prompt'], 4444444444)
      // console.log(this.$refs.editor.getHtml())
      // 插入角色名称
      this.$refs.editor.insertMention(roleId, `${role.name}-${role.dress}-${role.angle}@`)
      console.log(this.$refs.editor.getHtml())
      this.showRolePopup = false
    },
    // 切换角色弹窗显示
    handleToggleRolePopup(show) {
      this.$nextTick(() => {
        this.showRolePopup = show
        if (show) {
          this.searchVal = ''
        }
      })
    },
    // 语言切换
    handleLanguageChange(text) {
      if (!text) {
        this.$baseMessage.error('提示词不能为空!')
        return
      }
      if (this.translating) {
        this.$baseMessage.error('翻译中,请稍后再试!')
        return
      }
      // 调用接口翻译
      this.translating = true
      chineseToEnglish({ translationText: text }).then(res => {
        this.$set(this.editForm, 'promptRichText', res.data['translation'])
        this.translating = false
      }).catch(() => {
        this.translating = false
      })
    },
    // 角色标签点击
    handleRoleTagClick(item) {
      this.showRolePopup = true
      this.$nextTick(() => {
        this.searchVal = item.name
      })
    },
    // 智能推荐
    handleRecommend() {
      // 先前台合并提示词字段
      const prompt = `${this.selectLens['shotSizeName'] || '全景'}-${this.selectLens['lensTimeName'] || '早上'}-${this.selectLens['scenery']}`
      // this.$set(this.editForm, 'prompt', prompt)
      this.$set(this.editForm, 'promptRichText', `<p>${prompt}</p>`)
    },
    // 提示词标签更多参数
    handleMoreTagClick() {
      this.$refs.more.show(this.editForm)
    },
    // 格式化子标签显示
    formatterSubTag() {
      const index = this.allTagsList.findIndex(item => item.id === this.activeTabs)
      return index !== -1 ? this.allTagsList[index].child : []
    },
    // 格式化提示词标签类
    formatterTagClass(item) {
      if (!this.editForm['promptTags']) return ''
      const selectTags = this.editForm['promptTags'].split(',') || []
      return selectTags.findIndex(val => val === item.id.toString()) !== -1 ? 'active' : ''
    },
    // 提示词标签未选中的选中用逗号隔开，已选中的取消选中
    handleTagClick(item) {
      // let selectTags = this.editForm['promptTags'] ? this.editForm['promptTags'].split(',') : []
      // if (selectTags.findIndex(val => val === item.id.toString()) === -1) {
      //   selectTags.push(item.id)
      //   this.selectTagsList.push(item)
      //   // 同时插入提示词输入框
      //   this.$refs.editor.insertText(item.name)
      // } else {
      //   selectTags = selectTags.filter(val => val !== item.id.toString())
      //   this.selectTagsList = this.selectTagsList.filter(val => val.id !== item.id.toString())
      //   // 同时删除提示词输入框中内容
      // }
      // this.$set(this.editForm, 'promptTags', selectTags.join(','))
      // 同时插入提示词输入框
      this.$refs.editor.insertText(item.name)
    },
    // 更多标签点击保存
    handleMoreTagSave(data) {
      // 刷新标签列表
      this.queryPromptTagsList()
      // this.selectTagsList = data
      // this.$set(this.editForm, 'promptTags', data.map(item => item.id).join(','))
    },
    // 参考素材上传成功
    handleSuccess(response) {
      if (response['code'] === 200) {
        this.$set(this.editForm, 'referenceMaterial', response.data.id)
      }
    },
    // 参考素材文件删除
    handleRemove() {
      if (this.isSelectLens) {
        // 选择镜头的方式添加的图片，只需要清空字段值即可
        this.$set(this.editForm, 'referenceMaterial', '')
      } else {
        deleteFile(this.editForm['referenceMaterial']).then(res => {
          this.$set(this.editForm, 'referenceMaterial', '')
        })
      }
    },
    // 提示词全屏
    handleTogglePromptFull() {
      // console.log(this.$refs.editor, 7878);
      this.$refs.editor.insertRoleTag('测试角色121212')
      // if (!fullscreen.isEnabled) {
      //   this.$baseMessage.error('开启全屏失败')
      //   return false
      // }
      // fullscreen.toggle(this.$refs.prompt)
    },
    // 选择镜头选中
    handleLensCheck(data) {
      console.log(data)
      // 将镜头的图片id添加到参考素材中
      this.$set(this.editForm, 'referenceMaterial', data[0]['imageId'])
    },
    // 复制提示词
    async handleCopyPrompt(text) {
      if (!text) {
        this.$baseMessage.error('文本为空!')
        return
      }
      if (navigator.clipboard && navigator.clipboard.writeText) {
        // 使用Clipboard API
        try {
          await navigator.clipboard.writeText(text)
          this.$baseMessage.success('文本已复制到剪切板')
        } catch (err) {
          // 回退到document.execCommand
          document.execCommand('copy', false, text)
          this.$baseMessage.success('文本已复制到剪切板')
        }
      } else {
        // 直接使用document.execCommand作为回退方案
        document.execCommand('copy', false, text)
        this.$baseMessage.success('文本已复制到剪切板')
      }
    },
    // 画面比例切换
    handleScaleChange(val) {
      // 非宽高比链接下不用切换宽高
      if (this.editForm['isLink'] !== '1') return
      switch (val) {
        case '1':
          // 21 : 9
          this.$set(this.editForm, 'imageWidth', 850)
          this.$set(this.editForm, 'imageHeight', 364)
          break
        case '2':
          // 16: 9
          this.$set(this.editForm, 'imageWidth', 850)
          this.$set(this.editForm, 'imageHeight', 478)
          break
        case '3':
          // 3 : 2
          this.$set(this.editForm, 'imageWidth', 850)
          this.$set(this.editForm, 'imageHeight', 567)
          break
        case '4':
          // 4: 3
          this.$set(this.editForm, 'imageWidth', 816)
          this.$set(this.editForm, 'imageHeight', 612)
          break
        case '5':
          // 1 : 1
          this.$set(this.editForm, 'imageWidth', 624)
          this.$set(this.editForm, 'imageHeight', 624)
          break
        case '6':
          // 3 : 4
          this.$set(this.editForm, 'imageWidth', 612)
          this.$set(this.editForm, 'imageHeight', 816)
          break
        case '7':
          // 2 : 3
          this.$set(this.editForm, 'imageWidth', 567)
          this.$set(this.editForm, 'imageHeight', 850)
          break
        case '8':
          // 9 : 16
          this.$set(this.editForm, 'imageWidth', 478)
          this.$set(this.editForm, 'imageHeight', 850)
          break
      }
    },
    // 图片宽高链接点击
    handleLinkChange(val) {
      this.$set(this.editForm, 'isLink', val === '1' ? '0' : '1')
    },
    // 生成随机种子
    handleRandomGenerate() {
      // 生成0-999999999999999 的随机数
      const randomNum = Math.floor(Math.random() * Math.pow(10, 15))
      this.$set(this.editForm, 'seed', randomNum)
    },
    // 删除生成历史
    handleDeleteGenerate(item) {
      this.$baseConfirm('确定删除该条生成历史吗?', '提示', async() => {
        const { code, msg } = await deleteGenerateHistory({ taskId: item['taskId'], frameId: item['frameId'] })
        code === 200 ? this.$baseMessage.success(msg || '删除成功!') : this.$baseMessage.error(msg || '删除失败!')
        this.queryGenerateHistory()
      })
    },
    // 一键清空生成历史
    handleClearGenerate() {
      this.$baseConfirm('确定清空所有生成历史吗?', '提示', async() => {
        const { code, msg } = await clearGenerateHistory({ frameId: this.editForm['id'] || this.editForm['frameId'] })
        code === 200 ? this.$baseMessage.success(msg || '删除成功!') : this.$baseMessage.error(msg || '删除失败!')
        this.queryGenerateHistory()
      })
    },
    // 下载镜头图片
    handleDownloadLensFrameImage() {
      if (this.generatingList.length === 0) {
        if (!this.currentHistoryImageData['imageId']) {
          this.$baseMessage.error('当前没有图片可下载!')
          return
        }
        const downloadUrl = `${baseURL}${commonSaveFile}${this.currentHistoryImageData['imageId']}`
        const link = document.createElement('a')
        link.href = downloadUrl
        link.download = `${this.currentHistoryImageData['frameNo']}.jpg` // 可以根据需要修改文件名
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
      } else {
        const currentGenerateImageData = this.generatingList[this.currentGenerateImage]
        if (!currentGenerateImageData['imageId']) {
          this.$baseMessage.error('当前没有图片可下载!')
          return
        }
        const downloadUrl = `${baseURL}${commonSaveFile}${currentGenerateImageData['imageId']}`
        const link = document.createElement('a')
        link.href = downloadUrl
        link.download = `${currentGenerateImageData['frameNo']}.jpg` // 可以根据需要修改文件名
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
      }
    },
    // 设为镜头
    async handleSetLens(e, val) {
      if (e === '00') {
        const { code, msg } = await setLensFrame({ frameId: this.editForm['id'] || this.editForm['frameId'], imageId: val['imageId'] })
        code === 200 ? this.$baseMessage.success(msg || '设置分镜镜头成功!') : this.$baseMessage.error(msg || '设置分镜镜头失败!')
      } else {
        const { code, msg } = await cancelLensFrame({ frameId: this.editForm['id'] || this.editForm['frameId'], imageId: val['imageId'] })
        code === 200 ? this.$baseMessage.success(msg || '取消分镜镜头成功!') : this.$baseMessage.error(msg || '取消分镜镜头失败!')
      }
      // 直接选中设置封面的第一张
      this.currentHistoryImage = 0
      // 取消生成历史的选中下标
      this.currentGenerateHistoryImageId = null
      // 刷新数据
      this.queryLensData()
    },
    // 预览界面-放大查看镜头图片
    handleFullLensFrame() {
      if (this.generatingList.length > 0) {
        // 文生图成功之后的放大
        const currentGenerateImageData = this.generatingList[this.currentGenerateImage]
        if (!currentGenerateImageData['imageId']) {
          this.$baseMessage.error('当前没有图片可放大查看!')
          return
        }
        this.previewImageUrl = this.downloadUrl + currentGenerateImageData['imageId']
      } else {
        // 普通镜头的放大
        if (!this.currentHistoryImageData['imageId']) {
          this.$baseMessage.error('当前没有图片可放大查看!')
          return
        }
        this.previewImageUrl = this.downloadUrl + this.currentHistoryImageData['imageId']
      }
      this.showImageViewer = true
    },
    // 选中生成之后的图片
    handleGenerateSelectImage(item, index) {
      this.currentGenerateImage = index
    },
    // 上传镜头图片
    handleUploadLens(type) {
      this.isLensUpload = type
      this.$refs.fileInput.value = null
      this.$refs.fileInput.click()
    },
    // 图片上传选中文件
    handleFileChange(e) {
      const file = e.target.files[0]
      if (this.isLensUpload) {
        // 镜头图片上传
        const formData = new FormData()
        formData.append('file', file)
        formData.append('frameId', this.editForm.id)
        uploadFrameImage(formData).then(_ => {
          this.queryLensData()
        })
      } else {
        // 参考材料本地图片上传
        const formData = new FormData()
        formData.append('file', file)
        uploadFile(formData).then(res => {
          this.$set(this.editForm, 'referenceMaterial', res.data.id)
        })
      }
    },
    // 生成历史图片点击
    handleSelectImage(item, subItem) {
      this.currentHistoryImageData = item
      this.$set(this.currentHistoryImageData, 'imageId', subItem.imageId)
      this.$set(this.currentHistoryImageData, 'currentFrame', subItem['currentFrame'])
      this.currentGenerateHistoryImageId = subItem.imageId
      // 清空历史镜头选中
      this.currentHistoryImage = null
      // 清空选中的生成之后的图片id
      this.currentGenerateImage = null
      // 清空生成历史列表
      this.generatingList = []
      // 清空默认选中的生成历史
      this.generateHistoryRecurrence = []
    },
    // 生成历史图片按钮
    handleCommand(command, item, subItem) {
      switch (command) {
        case '1':
          this.editForm.promptRichText = item.promptRichText
          break
        case '2':
          this.editForm = item
          break
        case '3':
          this.previewImageUrl = this.downloadUrl + subItem.imageId
          this.showImageViewer = true
          break
        default:
          break
      }
    },
    // 开始生成
    startGenerate() {
      this.$refs.form.validate(async(valid) => {
        if (valid) {
          if (!this.editForm.frameId) {
            this.$set(this.editForm, 'frameId', this.editForm['id'])
          }
          delete this.editForm['id']
          // 将当前最新的输入框的文本赋值给prompt
          this.$set(this.editForm, 'prompt', htmlToText(this.$refs.editor.getHtml()))
          textToImages(this.editForm).then(_ => {
            this.generateLoading = true
            // 清空生成历史下标
            this.currentGenerateHistoryImageId = null
            // 清空选中的历史镜头下标
            this.currentHistoryImage = null
            this.generatingList = []
            for (let i = 0; i < this.editForm.createNum; i++) {
              this.generatingList.push({ ...this.editForm, imageId: '' })
            }
            // 判断当前任务是否在排队
            if (this.queueRemaining > 0) {
              this.$notify({
                title: '排队提示',
                message: `前面存在${this.queueRemaining}条任务,生成时间可能较长,请耐心等待~`,
                type: 'warning'
              })
            }
          })
        }
      })
    },
    // 开启webSocket 监听任务
    handleWs() {
      this.ws = new WS({
        url: process.env.NODE_ENV === 'development' ? `${wsUrl}${this.username}` : `${wsUrl}websocket/${this.username}`
      })
      // 事件监听
      this.ws.on('open', () => {
        console.log('连接成功')
      })
      this.ws.on('message', data => {
        // console.log('收到消息:', data)
        const jsonData = data.data
        switch (data.type) {
          case 'status':
            this.queueRemaining = jsonData['queue_remaining']
            // console.log('当前正在执行的任务数: ', this.queueRemaining)
            break
          case 'progress':
            console.log('进度消息', jsonData)
            // this.generateLoading = true
            break
          case 'executing':
            console.log('生成完成======', jsonData)
            if (jsonData && !jsonData['node']) {
              // 任务完成
              this.generateLoading = false
              // 更新生成历史
              this.queryGenerateHistory()
              // 根据镜头id判断，消息是否返回时当前镜头的任务
              console.log('当前任务id', jsonData['frameId'], '当前镜头id', this.editForm['frameId'])
              if (jsonData['frameId'] !== this.editForm['frameId']) return
              for (let i = 0; i < this.generatingList.length; i++) {
                const item = this.generatingList[i]
                const data = jsonData['result'][i]
                this.$set(item, 'imageId', data['imageId'])
                this.$set(item, 'taskStatus', '01')
              }
              console.log('生成列表', this.generatingList)
              // 默认选中第一张
              this.currentGenerateImage = 0
            }
            break
          case 'execution_error':
            console.log(jsonData, '生成失败')
            this.generateLoading = false
            if (jsonData && !jsonData['node']) {
              // 根据镜头id判断，消息是否返回时当前镜头的任务
              if (jsonData['frameId'].toString() !== this.editForm['frameId'].toString()) return
              // 将所有生成中的图片状态改为失败
              if (this.generatingList.length === 0) return
              this.generatingList.forEach(item => {
                item.imageId = ''
              })
            }
            break
          case 'execution_start':
            this.generateLoading = true
            break
        }
      })
      this.ws.on('reconnect', count => console.log(`第 ${count} 次重连...`))
      this.ws.on('error', error => {
        console.log(error, '连接失败')
        this.generateLoading = false
        // 将所有生成中的图片状态改为失败
        if (this.generatingList.length === 0) return
        this.generatingList.forEach(item => {
          item.imageId = ''
        })
      })
      this.ws.on('close', close => {
        console.log(close, '连接关闭')
        this.generateLoading = false
        // 将所有生成中的图片状态改为失败
        if (this.generatingList.length === 0) return
        this.generatingList.forEach(item => {
          item.imageId = ''
        })
      })
    },
    // 格式化画面比例显示
    formatterPicture(val) {
      return this.pictureScaleList.find(item => item.code === val).name
    },
    // 格式化角色显示
    formatterRoleName(val) {
      if (!val) return '-'
      const strArr = []
      val.forEach(item => {
        strArr.push(item.name)
      })
      return strArr.join('、')
    },
    // 添加镜头
    async handleAddLens(item, index) {
      // this.$baseConfirm('确认添加镜头?', '提示', async() => {
      //
      // })
      const params = {}
      if (item) {
        // 每个镜头前面添加
        this.$set(params, 'frameId', item['id'])
        this.$set(params, 'frameBeforeOrAfter', '01')
      } else {
        // 最后一个镜头后面添加
        this.$set(params, 'frameId', this.allLensList[this.allLensList.length - 1].id)
        this.$set(params, 'frameBeforeOrAfter', '02')
      }
      await addLensFrame(params)
      // 重新查询镜头数据
      this.lensFrameChangeReloadData(!item ? index + 1 : index)
    },
    // 选中镜头
    handleSelectLens(index) {
      if (this.currentLensIndex === index) return
      this.currentLensIndex = index
      // 组合镜头数据
      this.handleShotDataCombination(index)
      // 清空正在生成数组列表
      this.generatingList = []
      // 清空选中的生成历史图片id
      this.currentGenerateHistoryImageId = null
      // 清空选中的生成之后的图片id
      this.currentGenerateImage = null
      // 默认选中历史镜头第一张
      this.currentHistoryImage = 0
      // 请空默认选中的生成历史
      this.generateHistoryRecurrence = []
      // 查询任务进度
      this.handleQueryProgress()
      // 如果选中镜头不存在随机种子,则手动生成
      if (this.$baseLodash.isEmpty(this.editForm['seed'])) {
        this.handleRandomGenerate()
      }
      this.queryLensSettingCoverHistory()
    },
    // 向上移动镜头
    handleLenUp(item, index) {
      if (index === 0) {
        this.$baseMessage.error('已经是第一个镜头!')
        return
      }
      this.$baseConfirm('确认将该镜头向上移动?', '提示', async() => {
        // 调用接口移动镜头
        const { code, msg } = await moveLensFrame({ frameBeforeOrAfter: '01', frameId: item['id'] })
        code === 200 ? this.$baseMessage.success(msg || '向上移动成功!') : this.$baseMessage.error(msg || '向上移动失败!')
        // 选中上移
        this.lensFrameChangeReloadData(index - 1)
      })
    },
    // 向下移动镜头
    handleLenDown(item, index) {
      if (index === this.allLensList.length - 1) {
        this.$baseMessage.error('已经是最后一个镜头!')
        return
      }
      this.$baseConfirm('确认将该镜头向下移动?', '提示', async() => {
        // 调用接口移动镜头
        const { code, msg } = await moveLensFrame({ frameBeforeOrAfter: '02', frameId: item['id'] })
        code === 200 ? this.$baseMessage.success(msg || '向下移动成功!') : this.$baseMessage.error(msg || '向下移动失败!')
        // 选中下移
        this.lensFrameChangeReloadData(index + 1)
      })
    },
    // 镜头顺序改变后刷新数据
    lensFrameChangeReloadData(index) {
      queryLensListByFrameId({ lensId: this.selectLens['lensId'] }).then(res => {
        this.allLensList = res.data
        // 组合镜头数据
        this.handleShotDataCombination(index)
        // 选中当前下标
        this.handleSelectLens(index)
        // this.$nextTick(() => {
        //   // 滑动到对应镜头的位置
        //   const element = document.getElementById(`lensFrame${index}`)
        //   element.scrollIntoView({ behavior: 'smooth' })
        // })
      })
    },
    // 删除镜头
    handleLensFrameDelete(item) {
      this.$baseConfirm('确认删除该镜头?', '提示', async() => {
        // 调用接口删除镜头
        const { code, msg } = await deleteLensFrame({ frameId: item['id'] })
        code === 200 ? this.$baseMessage.success(msg || '删除成功!') : this.$baseMessage.error(msg || '删除失败!')
        // 刷新数据
        this.lensFrameChangeReloadData(this.currentLensIndex === this.allLensList.length - 1 ? this.currentLensIndex - 1 : this.currentLensIndex)
      })
    },
    // 图片历史镜头记录点击
    handleSelectHistory(index) {
      this.currentHistoryImage = index
      this.currentHistoryImageData = this.historyLensList[index] || {}
      // 清空正在生成数组列表
      this.generatingList = []
      // 清空生成历史图片下标
      this.currentGenerateHistoryImageId = null
      // 清空选中的生成之后的图片id
      this.currentGenerateImage = null
      // 清空默认选中的生成历史
      this.generateHistoryRecurrence = []
    },
    // 提示词复用
    handleReusePrompt(history) {
      console.log(history, 7878)
      this.editForm = this.$baseLodash.cloneDeep(history)
    },
    // 放大图片
    handleFull(data) {
      this.previewImageUrl = this.downloadUrl + data['imageId']
      this.showImageViewer = true
    },
    // 镜头数据组合
    handleShotDataCombination(index) {
      this.editForm = Object.assign({}, this.allLensList[index])
      if (!this.editForm['modelCode']) {
        this.$set(this.editForm, 'modelCode', '2')
      }
      if (!this.editForm['steps']) {
        this.$set(this.editForm, 'steps', 20)
      }
      if (!this.editForm['cfg']) {
        this.$set(this.editForm, 'cfg', 5.55)
      }
      if (!this.editForm['createNum']) {
        this.$set(this.editForm, 'createNum', '1')
      }
      if (!this.editForm['pictureScale']) {
        this.$set(this.editForm, 'pictureScale', '8')
      }
      if (!this.editForm['isLink']) {
        this.$set(this.editForm, 'isLink', '1')
      }
      if (!this.editForm['imageWidth']) {
        this.$set(this.editForm, 'imageWidth', 478)
      }
      if (!this.editForm['imageHeight']) {
        this.$set(this.editForm, 'imageHeight', 850)
      }
      if (!this.editForm['seed']) {
        this.handleRandomGenerate()
      }
      if (!this.editForm['promptRichText']) {
        this.$set(this.editForm, 'promptRichText', '')
      }
      console.log('当前文生图表单的内容:', this.editForm)
    },
    // 提示词区域切换
    promptFullChange() {
      this.isFullscreen = fullscreen.isFullscreen
    }
  }
}
